/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tces.view;

import com.itextpdf.text.*;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.*;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tces.controller.*;
import com.tces.model.*;
import java.io.ByteArrayOutputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author Arnold
 */
public class SubjectAction extends ActionSupport {

    private static final Logger log = Logger.getLogger(SubjectAction.class);
    private List<SubjectSchedule> instructorEvaluatedSubjectList;
    private User user;
    private String subjectScheduleID;
    private String oper;
    private List<Subject> subjectList;
    private String id, subjectName, subjectDescription, subjectLecUnits, subjectLabUnits, subjectType, subjectStatus;

    @Override
    public String execute() {
        try {
            subjectList = SubjectDAO.getSubjects();
        } catch (Exception ex) {
            log.error(ex);
        }
        return SUCCESS;
    }

    public String view() {
        try {
            user = (User) ActionContext.getContext().getSession().get("user");
            subjectList = SubjectDAO.getSubjects();
            log.info("SUBJECT LIST SIZE: " + subjectList.size());
        } catch (Exception ex) {
            log.error(ex);

        }
        return SUCCESS;
    }

    public String edit() {
        try {
            user = (User) ActionContext.getContext().getSession().get("user");
            log.info("subject status:" + subjectStatus);
            if (oper.equalsIgnoreCase("add")) {

                if (SubjectDAO.add(getSubject()) > 0) {
                    addActionMessage("Successfull insert of Subject (" + getSubject().getSubjectName() + ")");
                    return SUCCESS;
                } else {
                    addActionError("An error occured. Please contact your System Administrator");
                    return ERROR;
                }
            } else if (oper.equalsIgnoreCase("edit")) {
                if (SubjectDAO.update(getSubject()) > 0) {
                    addActionMessage("Successfull update of Subject (" + getSubject().getSubjectName() + ")");
                    return SUCCESS;
                } else {
                    addActionError("An error occured. Please contact your System Administrator");
                    return ERROR;
                }
            } /*
             * else if (oper.equalsIgnoreCase("del")) { if
             * (SubjectDAO.delete(Integer.parseInt(id)) > 0) {
             * addActionMessage("Successfull deletion of Subject Offering[ID:" +
             * id + "]"); return SUCCESS; } else { addActionError("An error
             * occured. Please contact your System Administrator"); return
             * ERROR; } }
             */ else {
                addActionMessage("Invalid operation!");
                return ERROR;
            }
        } catch (Exception ex) {
            addActionError(ex.toString());
            log.error(ex);
            return ERROR;
        }
    }

    public String viewInstructorsEvaluatedSubjects() {
        try {
            user = (User) ActionContext.getContext().getSession().get("user");
            if (user.getRoleName().equalsIgnoreCase("Guidance Counseling Officer")) {
                return ERROR;
            }
            if (user.getRoleName().equalsIgnoreCase("Instructor")) {
                instructorEvaluatedSubjectList = SubjectDAO.getInstructorEvaluatedSubjects(user.getUserIDNumber());
            } else {
                instructorEvaluatedSubjectList = SubjectDAO.getInstructorEvaluatedSubjects();
            }


        } catch (Exception ex) {
            log.error(ex);

        }
        return SUCCESS;
    }

    public String printInstructorsEvaluatedSubjects() throws Exception {
        try {
            user = (User) ActionContext.getContext().getSession().get("user");
            log.info("subjectScheduleID :" + subjectScheduleID);
            String[] scheduleID = subjectScheduleID.split(",");

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("application/pdf");
            // step 1
            Document document = new Document(PageSize.LETTER);
            Font normalFont = new Font(FontFamily.TIMES_ROMAN, 11, Font.NORMAL);
            Font smallerFontHeader = new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD);
            Font smallerFont = new Font(FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
            // step 2
            PdfWriter.getInstance(document, response.getOutputStream());
            // step 3
            document.open();
            float[] questionTableWidth = {6f, 1.3f, 1.3f, 1.3f, 1.3f, 1f};
            float[] headerWidth = {4f, 5f};
            float[] respondentWidth = {2.6f, 2f, 4f};
            float[] suggestionTableWidth = {1f, 6f};
            for (String ID : scheduleID) {
                SubjectSchedule subjectSchedule = SubjectScheduleDAO.getEvaluatedSchedule(Integer.parseInt(ID));
                if (subjectSchedule != null) {
//                    boolean newPageFlag=true;
//                    if(newPageFlag){
//                    document.newPage();
//                    newPageFlag=false;
//                    }
                    // step 4 - setting the document content
                    PdfPTable layoutTable = new PdfPTable(1);
                    layoutTable.setWidthPercentage(100);
                    layoutTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                    layoutTable.setSpacingBefore(0);
                    layoutTable.getDefaultCell().setBorder(0);
                    layoutTable.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
                    layoutTable.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
                    layoutTable.addCell(new Paragraph("PANPACIFIC UNIVERSITY NORTH PHILIPPINES", new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD)));
                    layoutTable.addCell(new Paragraph("Urdaneta City, Pangasinan", new Font(FontFamily.TIMES_ROMAN, 11, Font.NORMAL)));
                    layoutTable.addCell("  ");

                    PdfPCell headerTitleCell = new PdfPCell(new Paragraph("FACULTY PERFORMANCE EVALUATION SHEET", new Font(FontFamily.TIMES_ROMAN, 11, Font.BOLD, BaseColor.WHITE)));
                    headerTitleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    headerTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    headerTitleCell.setBackgroundColor(BaseColor.DARK_GRAY);
                    layoutTable.addCell(headerTitleCell);

                    //Add space
                    layoutTable.addCell("");

//            create a table for the header layout

                    PdfPTable headerTable = new PdfPTable(headerWidth);
                    headerTable.setWidthPercentage(100);
                    headerTable.getDefaultCell().setBorder(Rectangle.BOX);
                    headerTable.addCell(new Paragraph("NAME OF FACULTY :", normalFont));
                    headerTable.addCell(new Paragraph(subjectSchedule.getInstructorFullName().toUpperCase(), normalFont));
                    headerTable.addCell(new Paragraph("SUBJECT OFFERING :", normalFont));
                    headerTable.addCell(new Paragraph(subjectSchedule.getSubjectOfferingName().toUpperCase(), normalFont));
                    headerTable.addCell(new Paragraph("SUBJECT :", normalFont));
                    headerTable.addCell(new Paragraph(subjectSchedule.getSubjectCode().toUpperCase() + " - " + subjectSchedule.getSubjectDescription().toUpperCase(), normalFont));
                    headerTable.addCell(new Paragraph("QUALITATIVE INTERPRETATION :", normalFont));
                    headerTable.addCell(new Paragraph(subjectSchedule.getQualitativeInterpretation().toUpperCase(), normalFont));
                    headerTable.addCell(new Paragraph("TOTAL MEAN :", normalFont));
                    headerTable.addCell(new Paragraph(String.format(" %.2f", subjectSchedule.getTotalMean()) , normalFont));
                    layoutTable.addCell(headerTable);

                    //add space
                    layoutTable.addCell(" ");

                    //Create table for respondent count
                    int studentCount = SubjectScheduleDAO.getStudentCount(subjectSchedule.getSubjectScheduleID());

                    PdfPTable respondentNumberTable = new PdfPTable(respondentWidth);
                    respondentNumberTable.setWidthPercentage(50);
                    respondentNumberTable.getDefaultCell().setBorder(Rectangle.BOX);
                    respondentNumberTable.getDefaultCell().setBackgroundColor(BaseColor.DARK_GRAY);
                    respondentNumberTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
                    respondentNumberTable.addCell(new Paragraph("NUMBER OF STUDENTS :", normalFont));
                    respondentNumberTable.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                    respondentNumberTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                    respondentNumberTable.addCell(new Paragraph(String.valueOf(studentCount), normalFont));
                    respondentNumberTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                    respondentNumberTable.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                    respondentNumberTable.addCell(new Paragraph(" ", normalFont));
                    layoutTable.addCell(respondentNumberTable);

                    //add space
                    layoutTable.addCell(" ");
                    layoutTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

                    PdfPCell respondentTitleCell = new PdfPCell(new Paragraph("RESPONDENTS", new Font(FontFamily.TIMES_ROMAN, 11, Font.BOLD, BaseColor.WHITE)));
                    respondentTitleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    respondentTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    respondentTitleCell.setBackgroundColor(BaseColor.DARK_GRAY);
                    respondentTitleCell.setBorder(Rectangle.NO_BORDER);
                    layoutTable.addCell(respondentTitleCell);

                    //CAtegory spacer
                    PdfPCell categorySpaceCell = new PdfPCell(new Paragraph(" ", new Font(FontFamily.TIMES_ROMAN, 11, Font.BOLD, BaseColor.WHITE)));
                    categorySpaceCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    categorySpaceCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    categorySpaceCell.setBackgroundColor(BaseColor.DARK_GRAY);
                    categorySpaceCell.setBorder(Rectangle.NO_BORDER);

                    PdfPCell categoryTitleCell;

                    //category list
                    List<Category> categoryList = CategoryDAO.getActiveCategories();
                    for (Category cat : categoryList) {
                        //Category Title
                        categoryTitleCell = new PdfPCell(new Paragraph(cat.getCategoryName().toUpperCase() + "(" + cat.getCategoryPercentage() * 100 + ")", new Font(FontFamily.TIMES_ROMAN, 11, Font.BOLD, BaseColor.BLACK)));
                        categoryTitleCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        categoryTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        categoryTitleCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                        categoryTitleCell.setBorder(Rectangle.NO_BORDER);
                        layoutTable.addCell(categoryTitleCell);

                        //Question List
                        List<Question> questionList = QuestionDAO.getActiveQuestions(cat.getCategoryID());

                        PdfPTable questionTable = new PdfPTable(questionTableWidth);
                        questionTable.setWidthPercentage(100);
                        double categoryMean = 0;
                        boolean headerFlag = true;
                        for (Question question : questionList) {
                            if (headerFlag) {
                                questionTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                                questionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                                questionTable.addCell(new Phrase(" ", smallerFontHeader));
                                questionTable.getDefaultCell().setBackgroundColor(BaseColor.DARK_GRAY);
                                questionTable.getDefaultCell().setBorder(Rectangle.BOX);
                                for (Choice choice : ChoiceDAO.getActiveChoices(question.getQuestionID())) {
                                    questionTable.addCell(new Phrase(choice.getChoiceValue() + " (" + choice.getChoiceNumericValue() + ") ", smallerFontHeader));
                                }
                                questionTable.addCell(new Phrase("MEAN / UNIT", smallerFontHeader));
                                questionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                                questionTable.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                                headerFlag = false;
                            }
//                            questionTable.getDefaultCell().setBorder(Rectangle.BOX);
                            questionTable.addCell(new Phrase(question.getCategoriesQuestionsOrder() + ". " + question.getQuestionDescription(), smallerFont));
                            questionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                            double questionMean = 0;
                            for (Choice choice : QuestionDAO.getActiveQuestionsResponse(subjectSchedule.getSubjectScheduleID(), question.getQuestionID())) {
                                questionTable.addCell(new Phrase(String.valueOf(choice.getResponseCount()), smallerFont));
                                questionMean += choice.getResponseCount() * choice.getChoiceNumericValue();
                            }
                            questionTable.addCell(new Phrase(String.format(" %.2f", questionMean / studentCount), smallerFont));
                            categoryMean += questionMean / studentCount;
                            questionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                        }
                        questionTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        questionTable.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                        questionTable.getDefaultCell().setColspan(5);
                        questionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                        questionTable.addCell(new Phrase(cat.getCategoryName() + " Mean :", smallerFontHeader));
                        questionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                        questionTable.getDefaultCell().setColspan(0);
                        questionTable.addCell(new Phrase(String.format(" %.2f", categoryMean / questionList.size() * cat.getCategoryPercentage()), smallerFontHeader));

                        layoutTable.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                        layoutTable.addCell(questionTable);
                        //Category Footer
//                        layoutTable.getDefaultCell().setBackgroundColor(BaseColor.DARK_GRAY);
//                        layoutTable.addCell(categorySpaceCell);
                    }
                    //End Respondent bar
                    layoutTable.getDefaultCell().setBackgroundColor(BaseColor.DARK_GRAY);
                    layoutTable.addCell(categorySpaceCell);

                    //Suggestion section
                    layoutTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                    layoutTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                    layoutTable.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                    layoutTable.addCell(" ");

                    layoutTable.addCell(new Paragraph("SUGGESTION/COMMENTS :", new Font(FontFamily.TIMES_ROMAN, 11, Font.BOLD, BaseColor.BLACK)));

                    PdfPTable suggestionTable = new PdfPTable(suggestionTableWidth);
                    suggestionTable.setWidthPercentage(100);
                    for (String suggestion : SubjectScheduleDAO.getScheduleEvaluationSuggestion(subjectSchedule.getSubjectScheduleID())) {
                        suggestionTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        suggestionTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                        suggestionTable.addCell(" ");
                        suggestionTable.addCell("- " + suggestion);
                    }
                    layoutTable.addCell(suggestionTable);

                    document.add(layoutTable);
                    document.newPage();
                }
            }

            // step 5
            document.close();

        } catch (Exception ex) {
            log.info(ex);

            addActionError(ex.toString());
            throw (ex);
        }
        return NONE;
    }

//    public String redirectParameters() {
//        try {
//            user = (Student) ActionContext.getContext().getSession().get("student");
//            log.info("subjectScheduleID :" + subjectScheduleID);
//
//        } catch (Exception ex) {
//            log.error(ex);
//
//        }
//        return SUCCESS;
//    }
//    public String saveEvaluation() {
//        try {
//            user = (Student) ActionContext.getContext().getSession().get("student");
//            log.info("subjectScheduleID :" + subjectScheduleID);
//            if (SubjectDAO.checkDuplicate(Integer.parseInt(subjectScheduleID), user.getStudentID()) > 0) {
//                if (SubjectDAO.deleteEvaluation(Integer.parseInt(subjectScheduleID), user.getStudentID()) <= 0) {
//                    addActionError("Error deleting duplicate subject evaluation! Please check the log file for more info.");
//                }
//            }
//            HttpServletRequest request = ServletActionContext.getRequest();
//            List<Category> categoryList = CategoryDAO.getActiveCategories();
//            List<Question> questionList;
//            for (Category category : categoryList) {
//                questionList = QuestionDAO.getActiveQuestions(category.getCategoryID());
//                for (Question question : questionList) {
//                    if (request.getParameter("c" + category.getCategoryID() + "q" + question.getQuestionID()) != null) {
//                        log.info(request.getParameter("c" + category.getCategoryID() + "q" + question.getQuestionID()) + ":" + request.getParameter("c" + category.getCategoryID() + "q" + question.getQuestionID()));
//                        SubjectDAO.saveEvaluation(Integer.parseInt(subjectScheduleID), user.getStudentID(), question.getQuestionID(), Integer.parseInt(request.getParameter("c" + category.getCategoryID() + "q" + question.getQuestionID())));
//                    }
//
//                }
//            }
//
//            if (SubjectDAO.checkDuplicateSuggestion(Integer.parseInt(subjectScheduleID), user.getStudentID()) > 0) {
//                if (SubjectDAO.deleteEvaluationSuggestion(Integer.parseInt(subjectScheduleID), user.getStudentID()) > 0) {
//                    if (request.getParameter("suggestion").trim().isEmpty()) {
//                        if (SubjectDAO.saveEvaluationSuggestion(Integer.parseInt(subjectScheduleID), user.getStudentID(), request.getParameter("suggestion")) <= 0) {
//                            addActionError("Unable to save suggestion! Please check the log file for more info.");
//                        }
//                    }
//
//                } else {
//                    addActionError("Unable to delete the duplicate suggestions/comments.Please check the log file for more info.");
//                }
//            } else {
//                if (request.getParameter("suggestion").trim().isEmpty()) {
//                    if (SubjectDAO.saveEvaluationSuggestion(Integer.parseInt(subjectScheduleID), user.getStudentID(), request.getParameter("suggestion")) <= 0) {
//                        addActionError("Unable to save suggestion! Please check the log file for more info.");
//                    }
//                }
//            }
//
//
//        } catch (Exception ex) {
//            log.error(ex);
//
//        }
//        return SUCCESS;
//    }
    private Subject getSubject() {
        Subject subject = new Subject();
        if (subjectName != null) {
            subject.setSubjectName(subjectName);
        }
        if (subjectDescription != null) {
            subject.setSubjectDescription(subjectDescription);
        }
        if (subjectLecUnits != null) {
            subject.setSubjectLecUnits(Double.parseDouble(subjectLecUnits));
        }
        if (subjectLabUnits != null) {
            subject.setSubjectLabUnits(Double.parseDouble(subjectLabUnits));
        }
        if (subjectType != null) {
            subject.setSubjectType(Integer.parseInt(subjectType));
        }
        if (subjectStatus != null) {
            subject.setSubjectStatus(Integer.parseInt(subjectStatus));
        }
        if (id != null && !(id.equalsIgnoreCase("_empty"))) {
            log.info("" + id.equalsIgnoreCase("_empty"));
            subject.setSubjectID(Integer.parseInt(id));
        }

        return subject;
    }

    public List<SubjectSchedule> getInstructorEvaluatedSubjectList() {
        return instructorEvaluatedSubjectList;
    }

    public void setInstructorEvaluatedSubjectList(List<SubjectSchedule> instructorEvaluatedSubjectList) {
        this.instructorEvaluatedSubjectList = instructorEvaluatedSubjectList;
    }

    public String getSubjectScheduleID() {
        return subjectScheduleID;
    }

    public void setSubjectScheduleID(String subjectScheduleID) {
        this.subjectScheduleID = subjectScheduleID;
    }

    public List<Subject> getSubjectList() {
        return subjectList;
    }

    public void setSubjectList(List<Subject> subjectList) {
        this.subjectList = subjectList;
    }

    public String getOper() {
        return oper;
    }

    public void setOper(String oper) {
        this.oper = oper;
    }

    public String getSubjectDescription() {
        return subjectDescription;
    }

    public void setSubjectDescription(String subjectDescription) {
        this.subjectDescription = subjectDescription;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSubjectLabUnits() {
        return subjectLabUnits;
    }

    public void setSubjectLabUnits(String subjectLabUnits) {
        this.subjectLabUnits = subjectLabUnits;
    }

    public String getSubjectLecUnits() {
        return subjectLecUnits;
    }

    public void setSubjectLecUnits(String subjectLecUnits) {
        this.subjectLecUnits = subjectLecUnits;
    }

    public String getSubjectName() {
        return subjectName;
    }

    public void setSubjectName(String subjectName) {
        this.subjectName = subjectName;
    }

    public String getSubjectType() {
        return subjectType;
    }

    public void setSubjectType(String subjectType) {
        this.subjectType = subjectType;
    }

    public String getSubjectStatus() {
        return subjectStatus;
    }

    public void setSubjectStatus(String subjectStatus) {
        this.subjectStatus = subjectStatus;
    }
}
